package billetterie;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;

import thread.Train;
import thread.Voyageur;

public class BilletterieImpl extends UnicastRemoteObject implements Billeterie {
	
	/**
	 * 
	 */
	private static final long			serialVersionUID	= 1L;
	
	private HashMap<Trajet, Integer>	NombrePlace			= new HashMap<Trajet, Integer>();
	
	/**
	 * Initialise nombre disponible pour chaque trajet à 0.
	 */
	public BilletterieImpl(ArrayList<Trajet> trajets) throws RemoteException {
		for (Trajet t : trajets)
			NombrePlace.put(t, 0);
	}
	
	public synchronized void ajouterNombrePlace(Train train) {
		int nb = NombrePlace.get(train.getTrajet()) + train.getNbPlaceDisponible();
		NombrePlace.put(train.getTrajet(), nb);
	}
	
	public synchronized void reserverBillet(Voyageur voyageur) {
		while (NombrePlace.get(voyageur.getTrajet()) <= 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		Billet billet = new Billet(voyageur.getTrajet());
		while (billet == null) {
			try {
				wait();
				billet = new Billet(voyageur.getTrajet());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		try {
			System.out.println(">>>Impression du billet...");
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		voyageur.prendreBillet(billet);
		NombrePlace.put(voyageur.getTrajet(), NombrePlace.get(voyageur.getTrajet()) - 1);
		
	}
	
	public static void main(String args[]) {
		
		ArrayList<Trajet> trajets = new ArrayList<Trajet>();
		trajets.add(new Trajet("A", "B"));
		trajets.add(new Trajet("B", "A"));
		trajets.add(new Trajet("A", "C"));
		trajets.add(new Trajet("C", "A"));
		trajets.add(new Trajet("B", "C"));
		trajets.add(new Trajet("C", "B"));
		
		BilletterieImpl b = null;
		try {
			b = new BilletterieImpl(trajets);
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
		try {
			b = new BilletterieImpl(null);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		
		try {
			
			System.out.print("Installing security manager...");
			if (System.getSecurityManager() == null) {
				System.setSecurityManager(new SecurityManager());
			}
			System.out.println("done.");
			
			System.out.println("Creating and registering the stub...");
			Billeterie stub = (Billeterie) UnicastRemoteObject.exportObject(b, 0);
			Registry registry = LocateRegistry.getRegistry();
			registry.rebind("sncf", stub);
			System.out.println("done.");
			
		} catch (Exception re) {
			re.printStackTrace();
		}
		
	}
}
